package com.wpx.log.core.handler.field.render;

import java.lang.reflect.Field;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.EvaluationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.wpx.log.core.annotation.OpLogField;
import com.wpx.log.core.exception.InvalidValueException;
import com.wpx.log.util.Utils;

@Component
public class MappingRenderPolicy implements IFieldRenderPolicy {

	@Autowired
	private EvaluationContext beanFactoryEvaluationContext;
	
	@Override
	public Class<?> getType() {
		return MappingRenderPolicy.class;
	}

	@Override
	public Object render(Object value, OpLogField opLogField){
		String mapStr = opLogField.map().trim();
		if(StringUtils.isEmpty(mapStr)) {
			throw new InvalidValueException("\"map\" 空 为无效值!");
		}
		
		Map map = null;
		/**
		 * xxxx类全名-静态属性
		 */
		if(mapStr.indexOf("-") != -1) {
			String[] split = mapStr.split("-");
			Class<?> clazz = null;
			try {
				clazz = Class.forName(split[0]);
			} catch (ClassNotFoundException e) {
				throw new InvalidValueException("\""+split[0]+"\" 找不该类!", e);
			}
			Field field = null;
			try {
				field = clazz.getField(split[1]);
			} catch (Exception e) {
				throw new InvalidValueException("\""+split[1]+"\" 静态属性获取异常!", e);
			}
			
			try {
				field.setAccessible(true);
				map = (Map)field.get(null);
			} catch (Exception e) {				
				e.printStackTrace();
			} 
		}else if(mapStr.indexOf("@") == 0) {
			map = Utils.getValue(beanFactoryEvaluationContext, mapStr, true, Map.class);
		}else {
			throw new InvalidValueException("\"map\" 为无效值!");
		}
		
		return map.get(value);
	}

}
